package site.wetsion.galio.sdk.utils;

import site.wetsion.galio.sdk.common.GalioOauthAccessToken;
import site.wetsion.galio.sdk.common.UserDetails;
import java.util.Objects;

/**
 * @author weixin
 * @version 1.0
 * @CLassName AccessTokenHolderWrapper
 * @date 2019/5/21 2:42 PM
 */
public class AccessTokenHolderWrapper {

    private ResourceUtil resourceUtil;

    public AccessTokenHolderWrapper(ResourceUtil resourceUtil) {
        this.resourceUtil = resourceUtil;
    }

    /**
     * 获取token对象
     *
     * @Param [key]
     * @return com.dxy.data.rms.sdk.common.RmsOauthAccessToken
     **/
    public GalioOauthAccessToken get(String key) {
        GalioOauthAccessToken token = AccessTokenHolder.get(key);
        if (Objects.isNull(token)) {
            // 本地缓存为空，尝试从redis缓存读取，在存入本地缓存
            token = resourceUtil.getToken(key);
            if (Objects.nonNull(token)) {
                AccessTokenHolder.save(key, token);
            }
        }
        return token;
    }

    /**
     * 保存token进本地缓存和redis缓存
     *
     * @Param [key, value]
     * @return void
     **/
    public void save(String key, GalioOauthAccessToken value) {
        if (Objects.nonNull(value)) {
            AccessTokenHolder.save(key, value);
            resourceUtil.saveToken(value);
        }
    }

    public GalioOauthAccessToken remove(String key) {
        resourceUtil.removeToken(key);
        return AccessTokenHolder.remove(key);
    }

    public UserDetails getTokenUser(String key) {
        UserDetails userDetails = AccessTokenHolder.getUserByToken(key);
        if (Objects.isNull(userDetails)) {
            userDetails = resourceUtil.getAuthTokenUserDetails(key);
        }
        return userDetails;
    }

    public void saveUser(GalioOauthAccessToken token, UserDetails userDetails) {
        if (Objects.nonNull(userDetails)) {
            AccessTokenHolder.saveUser(token.getAccessToken(), userDetails);
            resourceUtil.saveTokenUserDetails(token, userDetails);
        }
    }

    public UserDetails removeTokenUser(String token) {
        UserDetails userDetails = resourceUtil.getAuthTokenUserDetails(token);
        resourceUtil.removeTokenUserDetails(token);
        AccessTokenHolder.removeUser(token);
        return userDetails;
    }

    public GalioOauthAccessToken getTokenByPlatformAndTokenStr(String platform, String tokenStr) {
        return resourceUtil.getAccessTokenByPlatFormAndTokenStr(platform, tokenStr);
    }

    public UserDetails getUserDetailsByPlatformAndTokenStr(String platform, String tokenStr) {
        return resourceUtil.getUserByPlatformAndTokenStr(platform, tokenStr);
    }
}
